{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python_defaultSpec_1595315346571",
   "display_name": "Python 3.7.4 64-bit ('tensorflow': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 张量排序\n",
    "import tensorflow as tf\n",
    "a = tf.random.shuffle(tf.range(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(5,), dtype=int32, numpy=array([4, 3, 2, 1, 0])>"
     },
     "metadata": {},
     "execution_count": 2
    }
   ],
   "source": [
    "tf.sort(a,direction='DESCENDING')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(5,), dtype=int32, numpy=array([4, 2, 1, 3, 0])>"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "tf.argsort(a,direction='DESCENDING')  # 返回排序后索引位置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = tf.random.uniform([3,3],maxval=10,dtype=tf.int32)\n",
    "res = tf.math.top_k(a,2)  # 返回排序前两个"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\narray([[1, 0],\n       [0, 2],\n       [1, 2]])>"
     },
     "metadata": {},
     "execution_count": 6
    }
   ],
   "source": [
    "res.indices  # 返回索引（argsort）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\narray([[7, 3],\n       [8, 6],\n       [5, 2]])>"
     },
     "metadata": {},
     "execution_count": 7
    }
   ],
   "source": [
    "res.values  # 返回数值（sort）"
   ]
  }
 ]
}